const mysql = require('mysql2/promise');
require('dotenv').config();

const dbConfig = {
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME
};

async function clearDatabase() {
    try {
        const connection = await mysql.createConnection(dbConfig);
        
        // 禁用外键检查
        await connection.query('SET FOREIGN_KEY_CHECKS = 0');

        try {
            // 删除所有表（按照依赖关系顺序）
            const tables = [
                'article_tags',    // 先删除关联表
                'comments',        // 删除依赖表
                'articles',        // 删除主要表
                'tags',           // 删除独立表
                'categories',
                'users'
            ];

            for (const table of tables) {
                try {
                    await connection.query(`DROP TABLE IF EXISTS ${table}`);
                    console.log(`Table ${table} dropped successfully`);
                } catch (error) {
                    console.error(`Error dropping table ${table}:`, error);
                }
            }

            console.log('All tables dropped successfully');

        } finally {
            // 重新启用外键检查
            await connection.query('SET FOREIGN_KEY_CHECKS = 1');
        }

        await connection.end();
        console.log('Database cleared successfully');

    } catch (error) {
        console.error('Error clearing database:', error);
    }
}

clearDatabase();